package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/gousing/logger"
	"github.com/gin-gonic/gin"
)

// go run ./examples/ginlog/main.go
//
//		Vister:
//		- curl -X GET http://127.0.0.1:8080/
//		- curl -X GET http://127.0.0.1:8080/error
//	  - Ctrl + C
func main() {
	data := bytes.NewBuffer(nil)
	log := logger.NewText(logger.NewStorage(data), &logger.Options{
		AddSource: true,
		Level:     logger.LevelDebug,
	})
	ginLog := log.ToGinLogger()
	gin.DefaultWriter = ginLog
	gin.DefaultErrorWriter = ginLog
	gin.DebugPrintRouteFunc = ginLog.DebugPrintRouteFunc
	gin.DebugPrintFunc = ginLog.DebugPrintFunc
	gin.DisableConsoleColor()
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.GET("/error", func(c *gin.Context) {
		c.AbortWithError(500, errors.New("test AbortWithError"))
	})
	server := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			fmt.Println("listen: %s\n", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	fmt.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		fmt.Println("Server Shutdown:", err)
	}
	fmt.Println("Server exiting")
	defer func() {
		err := log.Close()
		if err != nil {
			fmt.Println("log close error:", err)
		}
	}()
	fmt.Println(data.String())
}
